package com.example.usb.ai;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baidu.aip.util.Base64Util;
import com.example.usb.util.GsonUtils;
import com.lib.uvccamera.utils.DebugLog;
import com.lib.uvccamera.utils.FileUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.lib.uvccamera.utils.Aiconstant.API_KEY;
import static com.lib.uvccamera.utils.Aiconstant.APP_ID;
import static com.lib.uvccamera.utils.Aiconstant.SECRET_KEY;
import static com.lib.uvccamera.utils.Aiconstant.groupId;


/**
 * Created Date 2019/2/15
 *
 * @author liangkun
 * description：V3人脸库管理，增删改查
 */
public class AiLibManager {
    private static AiLibManager aiLibManager;
    private static AipFace aipFace;

    public static synchronized AiLibManager getInstance() {
        if (aiLibManager == null) {
            synchronized (AiLibManager.class) {
                if (aiLibManager == null) {
                    aiLibManager = new AiLibManager();
                }
//                getAipFace();
            }

        }
        return aiLibManager;
    }

    /**
     * 初始化人脸库对象
     */
    public static void initAipFace() {
        if (aipFace == null) {
            aipFace = new AipFace(APP_ID, API_KEY, SECRET_KEY);
            // 可选：设置网络连接参数
            aipFace.setConnectionTimeoutInMillis(10000);
            aipFace.setSocketTimeoutInMillis(10000);
        }
    }

    /**
     * 人脸检测
     */
    public AiV3Bean detectFace(String image) {

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("face_field", "age");
        options.put("max_face_num", "8");
//        options.put("face_type", "LIVE");
        options.put("face_field", "age,beauty,expression,faceshape,gender,glasses,landmark,race,quality,facetype");
        String imageType = "BASE64";
        // 人脸检测
        JSONObject res = aipFace.detect(image, imageType, options);
        AiV3Bean aiBean = GsonUtils.fromJson(res.toString(), AiV3Bean.class);
        return aiBean;
    }


    /**
     * 人脸搜索类似的脸
     *
     * @param image 唯一标志
     */
    public SearchFaceBean SearchFace(String image) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "NONE");
//       查找后返回的用户数量。返回相似度最高的几个用户，默认为1，最多返回20个。
        options.put("max_user_num", "8");
        String imageType = "BASE64";
        //从指定的group中进行查找 用逗号分隔，上限20个
        // 人脸搜索
        JSONObject res = aipFace.search(image, imageType, groupId, options);
        DebugLog.d(DebugLog.LOGHsc + " ---搜索---res-- " + res.toString());
        try {
            String error_code = res.getString("error_code");
            String error_msg = res.getString("error_msg");
            if (!error_code.equals("0")) {
                DebugLog.d(DebugLog.LOGHsc + " ---返回搜索结果---error_code-- " + error_code + " error_msg " + error_msg);
//                Constace.errorMsg = ErrorUtil.getErrorString(error_code);
                return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        SearchFaceBean searchFaceBean = GsonUtils.fromJson(res.toString(), SearchFaceBean.class);
        return searchFaceBean;
    }

    /**
     * 人脸注册
     *
     * @param image  图片数据
     * @param userId uerid 用户id（由数字、字母、下划线组成），长度限制128B
     */
    public FaceRegisterBean registerFacebyBase64(String image, String userId) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", "user's info");
        options.put("quality_control", "NORMAL");
        //图片质量控制 NONE: 不进行控制 LOW:较低的质量要求 NORMAL: 一般的质量要求 HIGH: 较高的质量要求 默认 NONE
//        options.put("liveness_control", "LOW");
        String imageType = "BASE64";
        // 人脸注册
        JSONObject res = aipFace.addUser(image, imageType, groupId, userId, options);
        DebugLog.d(DebugLog.LOGHsc + " ---registerFace ------------ " + res.toString());

        try {
            String error_code = res.getString("error_code");
            String error_msg = res.getString("error_msg");
            if (!error_code.equals("0")) {
                DebugLog.d(DebugLog.LOGHsc + " ---注册失败---error_code-- " + error_code + " error_msg " + error_msg);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        FaceRegisterBean faceRegisterBean = GsonUtils.fromJson(res.toString(), FaceRegisterBean.class);
        return faceRegisterBean;
    }

    /**
     * 更新人脸库
     *
     * @param image 图片
     * @return
     */
    public FaceRegisterBean updateFace(String image, String userId) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", "user's info");
        options.put("quality_control", "NORMAL");
//        options.put("liveness_control", "LOW");
        String imageType = "BASE64";
        String groupId = "group1";

        // 人脸更新
        JSONObject res = aipFace.updateUser(image, imageType, groupId, userId, options);
        FaceRegisterBean faceRegisterBean = GsonUtils.fromJson(res.toString(), FaceRegisterBean.class);
        return faceRegisterBean;

    }


    /**
     * TODO:单张删除或者多张删除
     *
     * @param
     */
    public void deleteFace(String userId, String faceToken) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        // 人脸删除
        JSONObject res = aipFace.faceDelete(userId, groupId, faceToken, options);
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    public AiV3GroupBean getGroup() {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("start", "0");
        options.put("num", "100");
        JSONObject res = aipFace.getGroupUsers(groupId, options);
        DebugLog.d(DebugLog.LOGHsc + " res ---getGroup " + res.toString());
        try {
            String error_code = res.getString("error_code");
            String error_msg = res.getString("error_msg");
            if (!error_code.equals("0")) {
                DebugLog.d(DebugLog.LOGHsc + " ---getGroup---error_code-- " + error_code + " error_msg " + error_msg);

                return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        AiV3GroupBean aiV3GroupBean = GsonUtils.fromJson(res.toString(), AiV3GroupBean.class);

        return aiV3GroupBean;
    }

    /**
     * 删除用户
     *
     * @param uerId 人脸唯一标识
     */
    public void deleteUser(String uerId) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        String groupId = "group1";
        // 删除用户
        JSONObject res = aipFace.deleteUser(groupId, uerId, options);
        try {
            String error_code = res.getString("error_code");
            if (error_code.equals("0")) {
                DebugLog.d(DebugLog.LOGHsc + " deleteUsere--删除成功 ");
            } else {
                DebugLog.d(DebugLog.LOGHsc + " deleteUsere--删除失败 error_code " + error_code);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 比较2个人脸的相似度
     *
     * @param headPath    人头路径1
     * @param headPahtTwo 人头路径2
     * @return 返回人脸对比的结果
     */
    public AiMatchV3Bean FaceCompare(String headPath, String headPahtTwo) {
        List<MatchRequest> list = new ArrayList<>();
        MatchRequest request1 = new MatchRequest(byteToString(headPath), "BASE64");
        MatchRequest request2 = new MatchRequest(byteToString(headPahtTwo), "BASE64");
        list.add(request1);
        list.add(request2);
        JSONObject match = aipFace.match(list);
        try {
            String error_code = match.getString("error_code");
            String error_msg = match.getString("error_msg");
            if (error_code.equals("0")) {
                DebugLog.d(DebugLog.LOGHsc + " FaceCompare-- ");
            } else {
                DebugLog.d(DebugLog.LOGHsc + " FaceCompare- error_code " + error_code + " error_msg " + error_msg);
                return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        AiMatchV3Bean matchV3Bean = GsonUtils.fromJson(match.toString(), AiMatchV3Bean.class);
        DebugLog.d(DebugLog.LOGHsc + " match " + match.toString());
        return matchV3Bean;

    }

    /**
     * 图片转为64位流
     *
     * @param headPath
     * @return
     */
    private String byteToString(String headPath) {
        String encode = "";
        try {
            encode = Base64Util.encode(FileUtils.readFileByBytes(headPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encode;
    }

    public void delete(String groupId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 传入可选参数调用接口
                HashMap<String, String> options = new HashMap<String, String>();

                // 删除用户组
                JSONObject res = aipFace.groupDelete(groupId, options);
                DebugLog.d("kunkun "+res.toString());

            }
        }).start();


    }
}
